package com.songlanyun.modules.im.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.utils.yunxin.YunXinImUtils;
import com.songlanyun.modules.im.dao.ImUserDAO;
import com.songlanyun.modules.im.dto.ImShopOnlineReqDTO;
import com.songlanyun.modules.im.dto.ImShopOnlineResDTO;
import com.songlanyun.modules.im.dto.ImUserInfoReqDTO;
import com.songlanyun.modules.im.dto.ImUserInfoResDTO;
import com.songlanyun.modules.im.entity.ImUser;
import com.songlanyun.modules.im.enums.YunXinEnums;
import com.songlanyun.modules.im.service.ImService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service("imService")
public class ImServiceImpl implements ImService {


    @Value("${im.AppSecret:1}")
    private String appSecret;

    @Value("${im.AppKey:1}")
    private String appKey;

    @Value("${im.WebUrl:1}")
    private String webUrl;

    @Resource
    private ImUserDAO imUserDAO;

    @Resource
    private YunXinImUtils yunXinImUtils;
    /**
     * im用户信息检查--未注册注册，已注册返回信息
     */
    @Override
    public R checkUserInfo(ImUserInfoReqDTO reqDTO) {

        // 查询本地用户信息

        QueryWrapper<ImUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", reqDTO.getUserId());

        ImUser imUser = imUserDAO.selectOne(queryWrapper);

        try {
            if (imUser == null) {
                JSONObject req = new JSONObject();
                // 本地库中未查询到用户信息，主动注册
                req.put("accid", reqDTO.getUserId());
                JSONObject res = yunXinImUtils.client(req, YunXinEnums.CREATE.getUrl());

                // 接受返回信息并保存
                imUser = new ImUser();
                imUser.setUserId(reqDTO.getUserId());
                imUser.setImAccid(res.getJSONObject("info").getString("accid"));
                imUser.setImToken(res.getJSONObject("info").getString("token"));
                imUser.setCreateTime(new Date());

                imUserDAO.insert(imUser);

            }

            ImUserInfoResDTO imUserInfoResDTO = new ImUserInfoResDTO();

            imUserInfoResDTO.setAccid(imUser.getImAccid());
            imUserInfoResDTO.setToken(imUser.getImToken());
            imUserInfoResDTO.setUserId(imUser.getUserId());

            return R.ok().put("data", imUserInfoResDTO);
        } catch (Exception e) {
            return R.error("该用户信息有误");
        }
    }

    @Override
    public R getKey() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appKey", appKey);
        jsonObject.put("appSecret", appSecret);
        return R.ok().put("data", jsonObject);
    }

    /**
     * 查询当前客服在线状态
     */
    @Override
    public R checkOnline(ImShopOnlineReqDTO reqDTO) {

        QueryWrapper<ImUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("shop_id", reqDTO.getShopId());
        // 匹配客服多商家
        queryWrapper.like("shop_id", reqDTO.getShopId());

        List<ImUser> imUsers = imUserDAO.selectList(queryWrapper);

        // 检测当前商家在线客服
        try {
            if (imUsers.size() > 0) {

                // 调用网易im接口查询当前客服是否在线
//                String[] shopAccids =
//                        imUsers.stream().map(imUser -> imUser.getImAccid()).toArray(String[]::new);
//                JSONObject req = new JSONObject();
//                req.put("accids", shopAccids);
//
//                JSONObject res = yunXinImUtils.client(req, YunXinEnums.CHECKONLINE.getUrl());
//                if (res.getInteger("code") != 200){
//                    // 该商家未注册客服或客服不在线
//                    ImShopOnlineResDTO imShopOnlineResDTO = new ImShopOnlineResDTO();
//                    imShopOnlineResDTO.setIsOnline(false);
//                    return R.ok().put("data", imShopOnlineResDTO);
//                }
//
//                JSONObject status = res.getJSONObject("data").getJSONObject("status");
//
//                List<String> accids = new ArrayList<>();
//
//                for (String accid : status.keySet()) {
//                    accids.add(accid);
//                }
//
//                // 获取在线客服首位
//                QueryWrapper<ImUser> callWrapper = new QueryWrapper<>();
//                callWrapper.eq("im_accid", accids.get(0));
//                ImUser imUser = imUserDAO.selectOne(callWrapper);

                // 获取商家绑定最多的客服
//                ImUser imUser = imUsers.get(0);

                // 客服在线时间 周一-周六,早8-晚6
                if (this.getCustomerTime()) {
                    ImShopOnlineResDTO imShopOnlineResDTO = new ImShopOnlineResDTO();
                    imShopOnlineResDTO.setIsOnline(false);

                    return R.error("当前时间客服不在线,客服在线时间为:周一至周六,8:00至18:00,请于客服在线时间内联系客服");
                }

                ImUser imUser = imUsers.stream().max(Comparator.comparing( item -> item.getShopId().split(",").length)).orElse(null);

                ImShopOnlineResDTO imShopOnlineResDTO = new ImShopOnlineResDTO();
                imShopOnlineResDTO.setToken(imUser.getImToken());
                imShopOnlineResDTO.setAccid(imUser.getImAccid());
                imShopOnlineResDTO.setIsOnline(true);

                return R.ok().put("data", imShopOnlineResDTO);

            } else {

                // 该商家未注册客服或客服不在线
                ImShopOnlineResDTO imShopOnlineResDTO = new ImShopOnlineResDTO();
                imShopOnlineResDTO.setIsOnline(false);
                return R.ok().put("data", imShopOnlineResDTO);
            }
        } catch (Exception e) {
            ImShopOnlineResDTO imShopOnlineResDTO = new ImShopOnlineResDTO();
            imShopOnlineResDTO.setIsOnline(false);
            return R.ok().put("data", imShopOnlineResDTO);
        }

    }

    public boolean getCustomerTime() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 获取当前星期几
        DayOfWeek dayOfWeek = now.getDayOfWeek();

        // 获取当前时间（仅包含时分秒）
        LocalTime time = now.toLocalTime();

        // 判断是否在周一到周六
        boolean isWeekday = dayOfWeek != DayOfWeek.SUNDAY;

        // 判断是否在早八到晚六之间
        LocalTime start = LocalTime.of(8, 0);
        LocalTime end = LocalTime.of(18, 0);
        boolean isWorkingHours = !time.isBefore(start) && !time.isAfter(end);

        // 输出结果
        return isWeekday && isWorkingHours;
    }

    /**
     * 客服登录
     */
    @Override
    public R customerLogin(ImUserInfoReqDTO reqDTO) {
        QueryWrapper<ImUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", reqDTO.getUserId());
//        queryWrapper.eq("shop_id", reqDTO.getShopId());

        ImUser imUser = imUserDAO.selectOne(queryWrapper);

        if (imUser == null || ObjectUtil.isNull(imUser.getImAccid())) {
            // 该用户未注册客服端-自动注册客服
            JSONObject req = new JSONObject();
            req.put("accid", reqDTO.getUserId());
            JSONObject res = yunXinImUtils.client(req, YunXinEnums.CREATE.getUrl());

            // 接受返回信息并保存
            imUser = new ImUser();
            imUser.setUserId(reqDTO.getUserId());
            imUser.setImAccid(res.getJSONObject("info").getString("accid"));
            imUser.setImToken(res.getJSONObject("info").getString("token"));
            imUser.setShopId(String.valueOf(reqDTO.getShopId()));
            imUser.setCreateTime(new Date());

            imUserDAO.insert(imUser);

        }

        ImUserInfoResDTO imUserInfoResDTO = new ImUserInfoResDTO();

        imUserInfoResDTO.setAccid(imUser.getImAccid());
        imUserInfoResDTO.setToken(imUser.getImToken());
        imUserInfoResDTO.setUserId(imUser.getUserId());
        String webLoginUrl = webUrl + "/?appkey=" + appKey + "&account=" + imUser.getImAccid() + "&token=" + imUser.getImToken();
        imUserInfoResDTO.setWebLoginUrl(webLoginUrl);

        return R.ok().put("data", imUserInfoResDTO);
    }


}
